package com.puppet.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Map;

/*
* 监听器类
* */
@Component
@Slf4j
public class EmailListener {
    @Autowired
    private JavaMailSender mailSender;

    /*
    * 监听邮件队列，发送邮件
    * 对指定的队列进行监听，并将数据注入给方法的形参
    * */
    @RabbitListener(queues = "email.queue")      /*加了这个注解就表示监听,设置要监听队列的名称*/
    public void sendEmail(Map<String,String> emailData){
        //为什么参数是map，因为发送消息的时候，发送的参数就是map
        log.info("监听到邮件队列，开始发送邮件，数据：{}", emailData);
        // 获取邮件信息
        String from = emailData.get("from");
        String to = emailData.get("to");
        String subject = emailData.get("subject");
        String content = emailData.get("content");

        //发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        //发送成功因此后，开发阶段就可以把这个代码注释了，不用每次都发送
        mailSender.send(message);
    }
}
